<template>
    <el-dialog v-model="show" title="付款申请" width="35%" align-center @close="handleClose">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
            status-icon>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="申请人:">
                        {{ userName }}
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="收款日期:">
                        {{ dateTime }}
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="申请金额:" prop="applyAmount">
                        <el-input v-model.number="ruleForm.applyAmount" placeholder="请输入申请金额" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="收款方:" prop="collectName">
                        <el-input v-model="ruleForm.collectName" placeholder="请输入收款方" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属公司:" prop="companyId">
                        <el-select style="width: 100%;" v-model="ruleForm.companyId" placeholder="请选择所属公司">
                            <el-option v-for="item in props.subsidiariesList" :key="item.id" :label="item.companyName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="摘要:" prop="summary">
                        <el-select style="width: 100%;" v-model="ruleForm.summary" placeholder="请选择所摘要">
                            <el-option v-for="item in props.initList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="申请原因:" prop="applyReason">
                        <el-input v-model="ruleForm.applyReason" placeholder="请输入申请原因" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="凭证上传:" prop="fileUrls">
                        <div style="display: flex; flex-wrap: wrap;" v-if="ruleForm.fileUrls.length != 0">
                            <div v-for="(item, index) in ruleForm.fileUrls" class="mr4" style="position: relative;"
                                :key="index">
                                <el-image style="width: 100px; height: 100px" :src="item" />
                                <el-icon @click="ruleForm.fileUrls.splice(index, 1)"
                                    style="cursor: pointer; color: red; position: absolute; top: 2px; right: 2px;font-size: 20px;">
                                    <CircleClose />
                                </el-icon>
                            </div>
                        </div>

                        <el-upload ref="designSketchRef" :show-file-list="false" drag :action="uploadImgUrl"
                            :headers="headers" multiple :auto-upload="true" :on-success="handleDesignSketchSuccess"
                            :before-upload="beforedeSignSketchUpload">
                            <div style="padding-top: 10px;">
                                <uploadStyle type="1" icon="PictureFilled" />
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" v-loading="loading" @click="handleSubmit(ruleFormRef)">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { getUserProfile } from "@/api/system/user";
import { addMiscellaneousExpensesApi } from '@/api/sj/financialManagement/miscellaneousExpenses'


import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import uploadStyle from '@/views/productManagement/designerTakesOrders/components/uploadStyle.vue';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList', 'type', 'subsidiariesList']);
const emits = defineEmits(['submit', 'close']);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);

const show = ref(false);
const dialogVisible = ref();
const userName = ref('');
const dateTime = ref('');
const loading = ref(false);


watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {
    }
}, { deep: true });

interface RuleForm {
    applyAmount: number | null
    summary: string
    collectName: string
    applyReason: string
    fileUrls: Array<string>
    companyId: number | null
};
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    applyAmount: null,
    summary: '',
    collectName: '',
    applyReason: '',
    fileUrls: [],
    companyId: null
});


const rules = reactive<FormRules>({
    applyAmount: [
        { required: true, message: '请输入申请金额', trigger: 'blur' },
        { type: 'number', min: 0, message: '请输入申请金额并且不能小于0', trigger: 'blur' },
    ],
    collectName: [
        { required: true, message: '请输入收款方', trigger: 'blur' },
    ],
    companyId: [
        {
            required: true,
            message: '请选择所属公司',
            trigger: ['blur', 'change'],
        },
    ],
    summary: [
        {
            required: true,
            message: '请选择摘要',
            trigger: ['blur', 'change'],
        },
    ],
    fileUrls: [
        { required: true, message: '请上传凭证', trigger: 'blur' },
    ]
});

/** 上传效果图 */
const handleDesignSketchSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    dialogVisible.value.close()
    ruleForm.fileUrls.push(response.data.url)
};


const beforedeSignSketchUpload: UploadProps['beforeUpload'] = () => {
    dialogVisible.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
};

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true;
            try {
                const { code } = await addMiscellaneousExpensesApi(ruleForm)
                if (code == 200) {
                    proxy?.$modal.msgSuccess('操作成功');
                    emits('submit', true);
                    loading.value = false;
                    handleClose();
                }
            } catch (error) {
                loading.value = false;
            }
        } else {
            console.log('error submit!', fields)
        }
    })
};

const getUser = async () => {
    const res = await getUserProfile();
    userName.value = res.data.user.userName
};


const handleClose = () => {
    ruleFormRef.value?.resetFields();
    emits('close');
};



onMounted(() => {
    getUser();

    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并补零
    const day = String(date.getDate()).padStart(2, '0'); // 补零
    dateTime.value = `${year}-${month}-${day}`;
})
</script>

<style lang="scss" scoped>
::v-deep .el-upload-dragger {
    padding: 0px 4px !important;
    height: 100px !important;
    width: 260px;
}

::v-deep .el-divider--horizontal {
    margin: 12px 0;
}
</style>